package com.qfmy.app.interceptor;

import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.interceptor
 * @date 2025/4/13
 * @description webApp的拦截器
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class webAppInterceptor implements HandlerInterceptor {

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头里面获取access token和refresh token
        String accessToken = request.getHeader("access-token");
        String refreshToken = request.getHeader("refresh-token");

        Claims claims = null;
        boolean tokenValid = false;

        //首先尝试解析access token
        if (accessToken != null) {
            try {
                claims = JwtUtil.parseToken(accessToken);
                tokenValid = true;
            } catch (ExpiredJwtException e) {
                log.info("Access token expired, trying to refresh");
            }
        }

        //如果access token过期或无效，尝试使用refresh token刷新access token
        if (!tokenValid && refreshToken != null) {
            try {
                Claims refreshClaims = JwtUtil.parseToken(refreshToken);
                //生成新的access token
                String newAccessToken = JwtUtil.refreshToken(refreshToken);
                //将新的access token添加到响应头中
                response.setHeader("new-access-token", newAccessToken);
                //更新claims信息
                claims = JwtUtil.parseToken(newAccessToken);
                tokenValid = true;
            } catch (Exception e) {
                log.error("Refresh token invalid", e);
                throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
            }
        }

        //如果token仍然无效，抛出异常
        if (!tokenValid) {
            throw new BaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }

        //获取用户信息
        String phone = (String) claims.get("phone");
        String username = (String) claims.get("username");
        Integer userId = (Integer) claims.get("userId");

        //创建LoginUser对象
        LoginUser loginUser = new LoginUser();
        loginUser.setPhone(phone);
        loginUser.setUsername(username);
        loginUser.setUserId(userId);

        //将用户信息保存在线程里面
        LoginUserHolder.setLoginUser(loginUser);
        return true;
    }

    /**
     * 在请求处理之后进行调用（Controller方法调用之后）
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除线程里面的用户信息
        LoginUserHolder.removeLoginUser();
    }
}